package com.pmcc.utils;

import org.apache.commons.lang.StringUtils;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码工具类
 *
 * Created by chuLiDong on 2018/8/27.
 */
public class BarcodeUtil {

    public static Map<String, String> Ean13(String codeNum, String path, String filePath) {
        Map<String, String> map = new HashMap<>();
        String url = "";
        if (StringUtils.isNotEmpty(codeNum)) {
            File targetFile = new File(path, filePath);
            boolean flag = true;
            if (!targetFile.exists()) {
                flag = targetFile.mkdirs();
            }
            if(flag){
                url = filePath + UUIDGenerator.getUUID() + ".png";
                File file = new File(path + url);
                try {
                    OutputStream ous = new FileOutputStream(file);
                    EAN13Bean ean13Bean = new EAN13Bean();
                    // 精细度
                    final int dpi = 150;
                    // module宽度
//        final double moduleWidth = UnitConv.in2mm(1.0f / dpi);
//        ean13Bean.setModuleWidth(moduleWidth);

                    String format = "image/png";
                    // 输出到流
                    BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                            BufferedImage.TYPE_BYTE_BINARY, false, 0);
                    // 生成条形码
                    ean13Bean.generateBarcode(canvas, codeNum);

                    // 结束绘制
                    canvas.finish();
                    map.put("url", url);
                    map.put("code", "1");
                    map.put("msg", "条形码生成成功！");
                    return map;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    map.put("code", "0");
                    map.put("msg", "条形码生成错误：未发现文件！");
                    return map;
                }catch (IOException e) {
                    e.printStackTrace();
                    map.put("code", "0");
                    map.put("msg", "条形码生成错误：文件 IO 异常！");
                    return map;
                    //throw new RuntimeException(e);
                }catch (IllegalArgumentException e){
                    e.printStackTrace();
                    map.put("code", "0");
                    map.put("msg", "条形码生成错误：条形码信息错误！");
                    return map;
                }
            }
        }
        return map;
    }

    public static void main(String[] args) {
//        String msg = "70255403";
        String codeNum = "6903244675147";
        String path = "/Users/chulidong/uploadFile/";
        Ean13(codeNum, path, "barCode");
    }
}
